package com.suning.park.admin.mgr.reportform.service.impl;

import com.google.common.collect.Lists;
import com.suning.park.dto.dao.CouponMapper;
import com.suning.park.dto.dao.CouponUserMapper;
import com.suning.park.dto.model.*;
import com.suning.park.admin.enums.CouponUseStateEnum;
import com.suning.park.admin.exception.BusinessFailException;
import com.suning.park.admin.mgr.reportform.model.TicketUsedDetailedExcel;
import com.suning.park.admin.mgr.reportform.model.TicketUsedExcel;
import com.suning.park.admin.mgr.reportform.service.TicketUsedService;
import com.suning.park.admin.util.CheckValue;
import com.suning.park.admin.util.DateUtil;
import com.suning.park.admin.util.page.PageInfo;
import com.suning.park.admin.util.excelTools.ExcelUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/*
 * Author:   niecheng
 * Date:     2017/1/19 11:20
 * Project:  park-pom
 * Description: //订单管理服务接口实现
 */
@Service(value = "ticketUsedServiceImpl")
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public class TicketUsedServiceImpl implements TicketUsedService {


    private static final Logger logger = LoggerFactory.getLogger(TicketUsedServiceImpl.class);

    @Autowired
    CouponMapper couponMapper;

    @Autowired
    CouponUserMapper couponUserMapper;


    @Override
    public PageInfo ajaxTicketUsedList(PageInfo pageInfo, Coupon coupon) {
        //TODO 获取停车券使用数据
        final CouponExample couponExampleHandle = getCouponExampleHandle(coupon);
        final int curCouponCount = queryCouponCount(couponExampleHandle);
        final List<Coupon> couponList = getCoupon(pageInfo, couponExampleHandle);
        pageInfo.setResultObject(couponList);
        pageInfo.setTotalResult( CheckValue.isEmpty(couponList) ? 0 : curCouponCount);
        return pageInfo;
    }

    @Override
    public byte[] exportTicketUsedList(Coupon coupon) {
        //TODO 导出停车券使用数据Excel
        final CouponExample couponExampleHandle = getCouponExampleHandle(coupon);
        final List<Coupon> coupons = couponMapper.selectByExample(couponExampleHandle);
        final List<Object> excelTicketUsedData = getTicketUsedExcelData(coupons);
        String sheetName = "停车券使用数据";
        String[] headers = {"序号","广场","券名称","券有效开始时间","券有有效结束时间","券点数","以领取","以使用","未使用"};
        return getByteArrayOutputStream(excelTicketUsedData, headers, sheetName).toByteArray();
    }

    /**
     * 获取要下载的停车券使用数据
     * @return
     */
    private List<Object> getTicketUsedExcelData(List<Coupon> coupons){
        List<Object> results = Lists.newArrayList();
        TicketUsedExcel ticketUsedExcel = null;
        for (Coupon coupon : coupons){
            ticketUsedExcel = new TicketUsedExcel();
            ticketUsedExcel.setId(coupon.getId());
            ticketUsedExcel.setAscription(coupon.getAscription());
            ticketUsedExcel.setCouponName(coupon.getCouponName());
            ticketUsedExcel.setStartTime(DateUtil.format(coupon.getStartTime(), DateUtil.datetimeFormat));
            ticketUsedExcel.setEndTime(DateUtil.format(coupon.getEndTime(), DateUtil.datetimeFormat));
            ticketUsedExcel.setTotal(String.valueOf(coupon.getTotal()));
            ticketUsedExcel.setObtained(String.valueOf(coupon.getUseCount()));
            ticketUsedExcel.setUsed(String.valueOf(coupon.getTotal()));
            ticketUsedExcel.setUnUsed(String.valueOf(coupon.getUseCount()));
            results.add(ticketUsedExcel);
        }
        return results;
    }


    /**
     * 分页获取优惠券
     * @param pageInfo         分页信息
     * @param couponExample 优惠券查询条件
     * @return
     */
    public List<Coupon> getCoupon(PageInfo pageInfo, CouponExample couponExample) {
        couponExample.setLimitStart((pageInfo.getCurrentPage() - 1) * pageInfo.getShowCount());
        couponExample.setLimitRows(pageInfo.getShowCount());
        return couponMapper.selectByExample(couponExample);
    }

    /**
     * 获取优惠券总量
     * @param couponExample 优惠券查询条件
     * @return
     */
    public int queryCouponCount(CouponExample couponExample) {
        final List<Coupon> coupons = couponMapper.selectByExample(couponExample);
        return CheckValue.isEmpty(coupons) ? 0 : coupons.size();
    }

    /**
     * 优惠券查询条件Example
     * @param coupon 优惠券查询条件
     * @return
     */
    public static CouponExample getCouponExampleHandle(Coupon coupon) {
        final CouponExample couponExample = new CouponExample();
        final CouponExample.Criteria criteria = couponExample.createCriteria();
        if( !CheckValue.isEmpty( coupon.getParkId() ) ){
            criteria.andParkIdEqualTo(coupon.getParkId());
        }
        if( !CheckValue.isEmpty(coupon.getCouponName())){
            criteria.andCouponNameEqualTo(coupon.getCouponName());
        }
        if ( !CheckValue.isEmpty(coupon.getStartTime())){
            criteria.andStartTimeGreaterThanOrEqualTo(coupon.getStartTime());
        }
        if ( !CheckValue.isEmpty(coupon.getEndTime())){
            try{
                criteria.andEndTimeLessThanOrEqualTo(DateUtil.getAddTime(coupon.getEndTime(), "235959"));
            }catch ( Exception e){
                logger.error("时间转换异常，错误信息：{}", e.getMessage());
                throw new BusinessFailException("系统异常");
            }
        }
        return couponExample;
    }

    /**
     * 优惠券查询条件
     * @param coupon 优惠券查询条件
     * @return
     */
    public static Map<String,Object> getTicketUsedQueryMap(Coupon coupon){
        final Map<String, Object> map = new HashMap<>();
        if( !CheckValue.isEmpty( coupon.getAscription() ) ){
            map.put("ascription", coupon.getAscription());
        }
        if( !CheckValue.isEmpty(coupon.getCouponName())){
            map.put("couponName", coupon.getCouponName());
        }
        if ( !CheckValue.isEmpty(coupon.getStartTime())){
            map.put("startTime", coupon.getStartTime());
        }
        if ( !CheckValue.isEmpty(coupon.getEndTime())) {
            try{
                map.put("endTime", DateUtil.getAddTime(coupon.getEndTime(), "235959"));
            }catch (Exception e){
                logger.error("时间转换异常，错误信息：{}", e.getMessage());
                throw new BusinessFailException("系统异常");
            }

        }
        return map;
    }

    /**
     * 导出数据字节缓存
     * @param dataList
     * @return
     */
    public ByteArrayOutputStream getByteArrayOutputStream(List<Object> dataList, String[] headers, String sheetName){
        ByteArrayOutputStream out = null;
        try {
            HSSFWorkbook workbook = ExcelUtil.exportExcelByListModel(sheetName, headers, dataList,null);
            out = new ByteArrayOutputStream();
            HSSFWorkbook hssWb = (HSSFWorkbook) workbook;
            hssWb.write(out);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return out;
    }

    @Override
    public PageInfo ajaxTicketUsedDetailedList(PageInfo pageInfo, String state, String couponId) {
        //TODO 获取明细
        final CouponUserExample couponUserExampleHandle = getCouponUserExampleHandle(state, couponId);
        final int curCouponUserCount = queryCouponUserCount(couponUserExampleHandle);
        final List<CouponUser> couponUserList = getCouponUser(pageInfo, couponUserExampleHandle);
        pageInfo.setResultObject(couponUserList);
        pageInfo.setTotalResult( CheckValue.isEmpty(couponUserList) ? 0 : curCouponUserCount);
        return pageInfo;
    }

    @Override
    public byte[] exportTicketUsedDetailed(String state, String couponId) {
        //TODO 导出停车券使用数据Excel
        final CouponUserExample couponUserExampleHandle = getCouponUserExampleHandle(state, couponId);
        final List<CouponUser> couponUsers = couponUserMapper.selectByExample(couponUserExampleHandle);
        final List<Object> excelTicketUsedDetailedData = getTicketUsedDetailedExcelData(couponUsers);
        String sheetName = "停车券使用明细";
        String[] headers = {"会员","券名称","活动名称","领券时间","用券时间","券状态"};
        return getByteArrayOutputStream(excelTicketUsedDetailedData, headers, sheetName).toByteArray();
    }

    /**
     * 获取要下载的停车券明细
     * @return
     */
    private List<Object> getTicketUsedDetailedExcelData(List<CouponUser> couponUsers){
        List<Object> results = Lists.newArrayList();
        TicketUsedDetailedExcel ticketUsedDetailedExcel = null;
        for (CouponUser couponUser : couponUsers){
            ticketUsedDetailedExcel = new TicketUsedDetailedExcel();
            ticketUsedDetailedExcel.setSnUserId(couponUser.getSnUserId());
            ticketUsedDetailedExcel.setCouponName(couponUser.getCouponName());
            ticketUsedDetailedExcel.setActionName(couponUser.getActionName());
            ticketUsedDetailedExcel.setGetTime(DateUtil.format(couponUser.getCreateTime(), DateUtil.datetimeFormat));
            ticketUsedDetailedExcel.setUseTime(DateUtil.format(couponUser.getLastTime(), DateUtil.datetimeFormat));
            ticketUsedDetailedExcel.setState(CouponUseStateEnum.getText(couponUser.getState()));
            results.add(ticketUsedDetailedExcel);
        }
        return results;
    }


    /**
     * 获取领取用户优惠券信息
     * @param state 优惠券状态
     * @param couponId 优惠券ID
     * @return
     */
    public CouponUserExample getCouponUserExampleHandle(String state, String couponId){
        final CouponUserExample couponUserExample = new CouponUserExample();
        final CouponUserExample.Criteria criteria = couponUserExample.createCriteria();
        if( !CheckValue.isEmpty(state)){
            criteria.andStateEqualTo(state);
        }
        if( !CheckValue.isEmpty(couponId)){
            criteria.andCouponIdEqualTo(couponId);
        }
        return couponUserExample;
    }

    /**
     * 获取用户领取优惠券总量
     * @param couponUserExample 优惠券领取查询条件
     * @return
     */
    public int queryCouponUserCount(CouponUserExample couponUserExample) {
        final List<CouponUser> couponUsers = couponUserMapper.selectByExample(couponUserExample);
        return CheckValue.isEmpty(couponUsers) ? 0 : couponUsers.size();
    }

    /**
     * 分页获取用户使用优惠券信息
     * @param pageInfo         分页信息
     * @param couponUserExample 优惠券使用查询条件
     * @return
     */
    public List<CouponUser> getCouponUser(PageInfo pageInfo, CouponUserExample couponUserExample) {
        couponUserExample.setLimitStart((pageInfo.getCurrentPage() - 1) * pageInfo.getShowCount());
        couponUserExample.setLimitRows(pageInfo.getShowCount());
        return couponUserMapper.selectByExample(couponUserExample);
    }

}
